<template>
  <ElDialog title="选择图标" v-model="isOpen" width="700px" append-to-body>
    <div class="icon-select-container" @click="handleClick">
      <div class="icon-wrapper" v-for="item in iconNames" :data-iconname="item">
        <component :is="item" style="width: 40px" />
        <label>{{ item }}</label>
      </div>
    </div>

    <template #footer>
      <el-button @click="cancel">取 消</el-button>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
import { ref, defineEmits } from "vue";
import * as ElementPlusIconsVue from "@element-plus/icons-vue";

const emit = defineEmits(["click"]);
const isOpen = ref(false);
const iconNames = ref(Object.keys(ElementPlusIconsVue));

function handleClick(e: any) {
  let name;
  if (e.target.dataset.iconname) {
    name = e.target.dataset.iconname;
  } else if (e.target.tagName.toLowerCase() === "svg" || e.target.tagName.toLowerCase() === "label") {
    const parent = e.target.parentElement;
    name = parent.dataset.iconname;
  }

  if (name) {
    cancel();
    emit("click", name);
  }
}

function init() {
  isOpen.value = true;
}

function cancel() {
  isOpen.value = false;
}

defineExpose({
  init,
});
</script>

<style lang="scss" scoped>
.icon-select-container {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 10px;

  .icon-wrapper {
    display: flex;
    flex-direction: column;
    align-items: center;

    &:hover {
      background-color: #eee;
      cursor: pointer;
      border-radius: 5px;
    }
  }
}
</style>
